import * as reduxStore from '@/redux/store';
import {Command} from '../constant';
import {Dispatch} from 'typings';
import {getActionProxy} from '@/redux/action-util';
import Action from './action';
import Taro from '@tarojs/taro';
import packageIAccountInformationMain from '../reducers/main';
import api from 'api';
export default (dispatch: Dispatch) => {
  const actions = {
    action: getActionProxy<typeof Action>(Action)(dispatch),

    /**
     * 初始化数据
     */
    async init() {
      let itemStr = Taro.getStorageSync('b2b-wechat@login');
      if (itemStr.user) {
        let customer = itemStr.user;
        const gameBase = await api.MemberController.getIplandMemberBase();
        if (gameBase.nickName) {
          customer.name = gameBase.nickName;
        }

        if (gameBase.headPortrait) {
          customer.pictureUrl = gameBase.headPortrait;
        }
        dispatch({
          type: Command.init,
          payload: {
            main: {
              defaultName: gameBase.nickName,
              defaultPictureUrl: gameBase.headPortrait,
              customer,
            },
          },
        });
      } else {
        actions.clean();
      }

      dispatch({
        type: Command.init,
        payload: {
          main: {
            isLogin: true,
            showAgree: false,
            showNewcomer: false,
            showNaviModal: false,
            showSettingModal: false,
          },
        },
      });
    },
    /**
     * 重置
     */
    async clean() {
      //@ts-ignore
      __TARO_ENV !== 'h5' && (await actions.unloadReducer());
      dispatch({type: Command.clean});
    },

    /**
     * 动态添加注入reducer
     */
    async loadReducer() {
      reduxStore.registerReducer({
        packageIAccountInformationMain,
      });
    },

    /**
     * 卸载reducer
     */
    async unloadReducer() {
      if (reduxStore.deregister) {
        reduxStore.deregister(['packageIAccountInformationMain']);
      } else {
        console.error('请在redux/store中实现deregister逻辑. ');
      }
    },
  };

  return {actions};
};

//create by moon https://github.com/creasy2010/moon
